package com.kldy8.kldyw.logre;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.kldy8.kldyw.Constant;
import com.kldy8.kldyw.Main2Activity;
import com.kldy8.kldyw.R;
import com.kldy8.kldyw.SystemSet;
import com.kldy8.kldyw.system.ServerApi;
import com.kldy8.kldyw.system.ServerCallBack;
import com.kldy8.kldyw.tools.TextUtil;
import com.kldy8.kldyw.tools.widget.CircleImageView;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.utils.SMSLog;
import okhttp3.Request;

import static com.mob.tools.utils.R.getStringRes;

public class ThreadRegisterActivity extends AppCompatActivity  implements View.OnClickListener
{

    // UI references.
    private AutoCompleteTextView mPhoneView;
//    private EditText mPasswordView;
    private EditText mVerifyView;
    private TextView nickName;
    private View mProgressView;
    private View mRegisterView;
    private ActionBar actionBar ;
    private Button next_btn;
    private Button verification_btn;

    private CircleImageView imageView;

    private String mphone;
    private String verification;
    private TextView user_accept_tv;
    Handler timeHandler = new Handler();
    private int count = 60;//倒计时
    private boolean check = true;
    private static InputMethodManager mInputMethodManager;

    private List<String> data_list_i;
    private List<String> data_list_ii;

    private ArrayAdapter<String> arr_adapter_i;
    private ArrayAdapter<String> arr_adapter_ii;

    Spinner spinner_i;
    Spinner spinner_ii;

    String[] companydata;
    String[] memberdata;
    String[] reg_type;

    private TimeCount time;

    private UserInfo userInfo = new UserInfo();

    //分享
    private OnLoginListener registerListener;
    private Platform platform;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        registerListener = tmpRegisterListener;
        platform = ShareSDK.getPlatform(tmpPlatform);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thread_register);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        initImageLoade();
        init();
    }

    private void initImageLoade()
    {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_empty)//设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.ic_empty)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.ic_empty)//设置图片加载/解码过程中错误时候显示的图片
//                .delayBeforeLoading(1000)//设置延时多少时间后开始下载
//                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)// 设置下载的资源是否缓存在SD卡中
//                .considerExifParams(true)// 是否考虑JPEG图像EXIF参数（旋转，翻转）
//                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)//设置图片以何种编码方式显示
//                .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
//                .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
//                .displayer(new FadeInBitmapDisplayer(1000))//是否图片加载好后渐入的动画时间
                .build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .memoryCacheExtraOptions(480, 800)//内存缓存文件的最大长宽
                .discCacheExtraOptions(480, 800, null)//本地缓存的详细信息
                .threadPoolSize(3)//线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY-2)//设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO)//设置任务的处理顺序
                .denyCacheImageMultipleSizesInMemory()//防止内存中图片重复
                .memoryCache(new LruMemoryCache(2*1024*1024))//设置自己的内存缓存大小   2M
                .memoryCacheSize(2*1024*1024)
                .memoryCacheSizePercentage(13)//内存缓存百分比
                .imageDownloader(new BaseImageDownloader(this))
                .imageDecoder(new BaseImageDecoder(true))//图片解码
                .defaultDisplayImageOptions(options)//是否使用默认的图片加载配置，null表示不使用
                .build();

        loader = ImageLoader.getInstance();
        loader.init(config);

    }


    String strSpi;
    String strSpii;
    int intSpi;
    int intSpii;
    long idSpi;
    long idSpii;

    ImageLoader loader;
    DisplayImageOptions options;


    private void init()
    {
        String gender = "";
        if(platform != null){
            gender = platform.getDb().getUserGender();
            if("m".equals(gender)){
                userInfo.setUserGender(UserInfo.Gender.MALE);
//                ivBoy.setVisibility(View.VISIBLE);
//                ivGril.setVisibility(View.INVISIBLE);
            }else{
                userInfo.setUserGender(UserInfo.Gender.FEMALE);
//                ivBoy.setVisibility(View.INVISIBLE);
//                ivGril.setVisibility(View.VISIBLE);
            }
            userInfo.setUserIcon(platform.getDb().getUserIcon());
            userInfo.setUserName(platform.getDb().getUserName());
            userInfo.setUserNote(platform.getDb().getUserId());
        }



        nickName = (TextView) findViewById(R.id.nickName);
        nickName.setText(userInfo.getUserName());
        imageView = (CircleImageView) findViewById(R.id.image);

        String headUrl =  userInfo.getUserIcon();
        loader.displayImage(headUrl, imageView,options);

        companydata = getResources().getStringArray(R.array.company_type);
        memberdata = getResources().getStringArray(R.array.member_type);
        reg_type  = getResources().getStringArray(R.array.reg_type);
        data_list_i = Arrays.asList(reg_type);
        data_list_ii = Arrays.asList(memberdata);

        spinner_i = (Spinner) findViewById(R.id.spinner1);

        spinner_ii = (Spinner) findViewById(R.id.spinner2);

        arr_adapter_i= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list_i);
        //设置样式
        arr_adapter_i.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


        arr_adapter_ii= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list_ii);
        //设置样式
        arr_adapter_ii.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //加载适配器
        spinner_i.setAdapter(arr_adapter_i);
        spinner_ii.setAdapter(arr_adapter_ii);
        spinner_i.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent,
                                               View view, int position, long id)
                    {

                        if (position == 1)
                        {
                            data_list_ii = Arrays.asList(companydata);

                        }
                        else
                        {
                            data_list_ii = Arrays.asList(memberdata);

                        }

                        strSpi = (String) spinner_i.getSelectedItem();
                        intSpi = position;
                        idSpi = id;

                        arr_adapter_ii= new ArrayAdapter<String>(ThreadRegisterActivity.this, android.R.layout.simple_spinner_item, data_list_ii);
                        //设置样式
                        arr_adapter_ii.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinner_ii.setAdapter(arr_adapter_ii);
                    }

                    public void onNothingSelected(AdapterView<?> parent)
                    {

                    }
                });


        spinner_ii.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent,
                                               View view, int position, long id)
                    {
                        strSpii = (String) spinner_ii.getSelectedItem();
                        intSpii =  SystemSet.getInstance().getAccountType().returnAccountTypeId(strSpii);
                        idSpii = id;
                    }

                    public void onNothingSelected(AdapterView<?> parent)
                    {

                    }
                });


        SMSSDK.initSDK(this, Constant.APP_KEY,  Constant.APP_SECRET);
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        mRegisterView=findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);
        mPhoneView= (AutoCompleteTextView) findViewById(R.id.phone_edt);
        mVerifyView= (EditText) findViewById(R.id.verification_edt);
//        mPasswordView= (EditText) findViewById(R.id.password_edt);

        user_accept_tv= (TextView) findViewById(R.id.user_accept_tv);
        next_btn=(Button)findViewById(R.id.next_btn);
        verification_btn=(Button)findViewById(R.id.verification_btn);
        verification_btn.setOnClickListener(this);
        next_btn.setOnClickListener(this);
//            user_accept_tv.setOnClickListener(this);

        time = new TimeCount(verification_btn,60000, 1000);//构造CountDownTimer对象

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        int id = item.getItemId();
        if (id == android.R.id.home)
        {
            this.finish();
        }
//        if (id == R.id.action_register)
//        {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.next_btn:
                showProgress(true);
                next_register();
                break;
            case R.id.verification_btn:
                if(check)
                {
                    getCode();

                }
                break;
            case R.id.user_accept_tv:
                Intent intent=new Intent();
//                    intent.setClass(RegisterActivity.this,UserAcceptActivity.class);
                this.startActivity(intent);
                break;
        }
    }

    private void next_register()
    {
        mPhoneView.setError(null);
        mVerifyView.setError(null);
//        mPasswordView.setError(null);
        mphone=mPhoneView.getText().toString();
        verification=mVerifyView.getText().toString();
//        password=mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

//        if (TextUtils.isEmpty(password) || !isPasswordValid(password)) {
//            mPasswordView.setError(getString(R.string.error_invalid_password));
//            focusView = mPasswordView;
//            cancel = true;
//            showProgress(false);
//
//        }
        // Check for a valid email address.
        if (TextUtils.isEmpty(mphone)) {
            mPhoneView.setError(getString(R.string.error_field_required));
            focusView = mPhoneView;
            cancel = true;
            showProgress(false);

        }else if (TextUtil.isEmpty(verification)) {
            mVerifyView.setError(getString(R.string.error_ver_required));
            focusView = mVerifyView;
            cancel = true;
            showProgress(false);

        }else if (!TextUtil.isMobileNumber(mphone)) {
            mPhoneView.setError(getString(R.string.error_invalid_email));
            focusView = mPhoneView;
            cancel = true;
            showProgress(false);

        }
        if (cancel)
        {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
            showProgress(false);
        }
        else
        {
//          SMSSDK.submitVerificationCode("86", mphone, verification);.
            TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
            String client_key = tm.getDeviceId();

            String register_way = ""+getIntent().getStringExtra("register_way");

            String access_token = platform.getDb().getToken();
            String openid  =  userInfo.getUserNote();


            ServerApi.thirdloginRegister(register_way, mphone, verification,""+intSpii, "" +intSpi ,client_key,access_token,openid,
                    new ServerCallBack()
                    {
                        @Override
                        public void onError(Request request, Exception e)
                        {
                            showProgress(false);
                            Toast.makeText(ThreadRegisterActivity.this,"网络错误，请稍后重试",Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onResponse(String response) throws JSONException
                        {
                            showProgress(false);
                            Log.e("......",response.toString());
//                            Toast.makeText(ThreadRegisterActivity.this,response.toString(),Toast.LENGTH_LONG).show();
                            JSONObject jsonObject = new JSONObject(response);
                            if ("0".equals(jsonObject.optString("code")))
                            {
                                JSONObject objectData = jsonObject.optJSONObject("data");
                                String username =  objectData.optString("username");
                                String token =  objectData.optString("token");
                                String member_id =  objectData.optString("member_id");

                                SystemSet.getInstance().setToken(token);
                                SystemSet.getInstance().setF_person(""+intSpi);
                                SystemSet.getInstance().setMember_id(member_id);

                                Intent i=new Intent();
                                i.setClass(ThreadRegisterActivity.this, Main2Activity.class);
                                startActivity(i);
                                overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                                return;
                            }
                            else if ("10006".equals(jsonObject.optString("code")))
                            {
                                Toast.makeText(ThreadRegisterActivity.this,"验证码错误",Toast.LENGTH_LONG).show();
                            }
                            else if ("10007".equals(jsonObject.optString("code")))
                            {
                                Toast.makeText(ThreadRegisterActivity.this,"用户名已存在",Toast.LENGTH_LONG).show();
                            }
                            else if ("10008".equals(jsonObject.optString("code")))
                            {
                                Toast.makeText(ThreadRegisterActivity.this,"用户类型非法",Toast.LENGTH_LONG).show();
                            }
                            else if ("10009".equals(jsonObject.optString("code")))
                            {
                                Toast.makeText(ThreadRegisterActivity.this,"电话号码格式错误",Toast.LENGTH_LONG).show();
                            }
                            else if ("10010".equals(jsonObject.optString("code")))
                            {
                                Toast.makeText(ThreadRegisterActivity.this,"电话号码已有绑定的账号",Toast.LENGTH_LONG).show();
                            }
                            else if ("10011".equals(jsonObject.optString("code")))
                            {
                                Toast.makeText(ThreadRegisterActivity.this,"密码格式不合法",Toast.LENGTH_LONG).show();
                            }
                            else
                            {
                                Toast.makeText(ThreadRegisterActivity.this,"注册失败，请填入正确资料",Toast.LENGTH_LONG).show();
                            }
                        }
                    });
        }

    }

    /**
     * 验证密码长度
     * @param password
     * @return
     */
    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }


    //获取验证码
    private void getCode()
    {
        mVerifyView.setError(null);
        mphone=mPhoneView.getText().toString();
        if(TextUtil.isEmpty(mphone)) {
            mPhoneView.setError(getString(R.string.isphone_null_toast));
            return;
        }
        if(!TextUtil.isMobileNumber(mphone)) {
            mPhoneView.setError(getString(R.string.isphone_not_toast));
            return;
        }
//            SMSSDK.getVerificationCode("86", mphone);
//            checkCompelte=false;
        time.start();//开始计时
        ServerApi.SMS(mphone,ServerApi.SMS_TYPE_REGISTER ,new ServerCallBack()
        {
            @Override
            public void onError(Request request, Exception e)
            {
                Log.e("onError",e.getMessage());
                Toast.makeText(ThreadRegisterActivity.this,"网络错误，请稍后重试",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onResponse(String response) throws JSONException
            {
                Log.e("response",response.toString());
                JSONObject object = new JSONObject(response);
                if ("0".equals(object.optString("code")))
                {
                    Toast.makeText(ThreadRegisterActivity.this,"发送成功，请查看手机验证码",Toast.LENGTH_LONG).show();
                }
                else if ("10002".equals(object.optString("code")))
                {
                    Toast.makeText(ThreadRegisterActivity.this,"此手机号码已注册",Toast.LENGTH_LONG).show();
                }
                else if ("10006".equals(object.optString("code")))
                {
                    Toast.makeText(ThreadRegisterActivity.this,"验证码错误",Toast.LENGTH_LONG).show();
                }
                else if ("10007".equals(object.optString("code")))
                {
                    Toast.makeText(ThreadRegisterActivity.this,"用户名已存在",Toast.LENGTH_LONG).show();
                }
                else if ("10008".equals(object.optString("code")))
                {
                    Toast.makeText(ThreadRegisterActivity.this,"用户类型非法",Toast.LENGTH_LONG).show();
                }
                else if ("10009".equals(object.optString("code")))
                {
                    Toast.makeText(ThreadRegisterActivity.this,"电话号码格式错误",Toast.LENGTH_LONG).show();
                }
                else if ("10010".equals(object.optString("code")))
                {
                    Toast.makeText(ThreadRegisterActivity.this,"电话号码已有绑定的账号",Toast.LENGTH_LONG).show();
                }
                else if ("10011".equals(object.optString("code")))
                {
                    Toast.makeText(ThreadRegisterActivity.this,"密码格式不合法",Toast.LENGTH_LONG).show();
                }
                else
                {
                    Toast.makeText(ThreadRegisterActivity.this,"注册失败，请填入正确资料",Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    /**
     * 重新获取验证码倒计时
     * */
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            count--;
            if (count > 0)
            {
                verification_btn.setText("重新获取(" + count + ")");
                verification_btn.setClickable(false);
                verification_btn.setTextSize(15);
                timeHandler.postDelayed(this, 1000);
            }
            else if (count == 0)
            {
                count = 60;
                check = true;
                verification_btn.setText("重新获取");
                verification_btn.setClickable(true);
                timeHandler.removeCallbacks(runnable, 1000);
            }
        }

    };

    /**
     * 获取验证码成功后执行的动作
     *
     * @param result
     * @param data
     */
    private void afterGet(final int result, final Object data) {
        runOnUiThread(new Runnable() {
            public void run() {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    check = false;
                    timeHandler.postDelayed(runnable, 1000);
                    Toast.makeText(ThreadRegisterActivity.this, "已将验证码发送到该手机！",
                            Toast.LENGTH_SHORT).show();
                } else {
                    ((Throwable) data).printStackTrace();
                    Throwable throwable = (Throwable) data;
                    // 根据服务器返回的网络错误，给toast提示
                    try {
                        JSONObject object = new JSONObject(
                                throwable.getMessage());
                        String des = object.optString("detail");
                        if (!TextUtils.isEmpty(des)) {
                            Toast.makeText(ThreadRegisterActivity.this, des,
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (JSONException e) {
                        SMSLog.getInstance().w(e);
                    }
                    // / 如果木有找到资源，默认提示
                    int resId = getStringRes(ThreadRegisterActivity.this,
                            "smssdk_network_error");
                    if (resId > 0) {
                        Toast.makeText(ThreadRegisterActivity.this, resId,
                                Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();

    }
    /**
     * TODO 跳转dialog
     */
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
            mRegisterView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mRegisterView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }
    /**
     * 验证码正确 进行页面跳转
     *
     * @param result
     * @param data
     */
    private void afterSubmit(final int result, final Object data) {
        runOnUiThread(new Runnable() {
            public void run() {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    Log.e("", "验证码正确");
                    count = 60;
                    check = true;
                    verification_btn.setText("重新获取");
                    timeHandler.removeCallbacks(runnable);
                    showProgress(true);
                    try {
//                        register(mPhoneView.getText().toString(),
//                                mPasswordView.getText().toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    mVerifyView.setError(null);
                    ((Throwable) data).printStackTrace();
                    mVerifyView.setError("验证码错误");
                }
            }
        });
    }
    // 隐藏软件盘
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {

            if (ThreadRegisterActivity.this.getCurrentFocus() != null
                    && ThreadRegisterActivity.this.getCurrentFocus().getWindowToken() != null) {
                mInputMethodManager.hideSoftInputFromWindow(ThreadRegisterActivity.this
                                .getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }


    private static OnLoginListener tmpRegisterListener;
    private static String tmpPlatform;

    public static final void setOnLoginListener(OnLoginListener login)
    {
        tmpRegisterListener = login;
    }

    public static final void setPlatform(String platName)
    {
        tmpPlatform = platName;
    }


    private static final int INTENT_ACTION_PICTURE = 0;
    private static final int INTENT_ACTION_CAREMA = 1;
    private static final int INTENT_ACTION_CROP = 2;
    private static final int LOAD_USER_ICON = 3;



}
